<?php

namespace app\store\model;

use app\common\model\OrderRefund as OrderRefundModel;

use app\store\model\User as UserModel;
use app\common\service\Message as MessageService;
use app\common\service\order\Refund as RefundService;
use app\common\enum\OrderType as OrderTypeEnum;
use think\Db;
/**
 * 售后单模型
 * Class OrderRefund
 * @package app\api\model
 */
class NeworderRefund extends OrderRefundModel
{
    /**
     * 获取售后单列表
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    // public function getList($query = [])
    // {
    //     // 查询条件：订单号
    //     if (isset($query['order_no']) && !empty($query['order_no'])) {
    //         $this->where('order.order_no', 'like', "%{$query['order_no']}%");
    //     }
    //     // 查询条件：起始日期
    //     if (isset($query['start_time']) && !empty($query['start_time'])) {
    //         $this->where('m.create_time', '>=', strtotime($query['start_time']));
    //     }
    //     // 查询条件：截止日期
    //     if (isset($query['end_time']) && !empty($query['end_time'])) {
    //         $this->where('m.create_time', '<', strtotime($query['end_time']) + 86400);
    //     }
    //     // 售后类型
    //     if (isset($query['type']) && $query['type'] > 0) {
    //         $this->where('m.type', '=', $query['type']);
    //     }
    //     // 处理状态
    //     if (isset($query['state']) && is_numeric($query['state'])) {
    //         $this->where('m.status', '=', $query['state']);
    //     }

    //     // 订单类型为商品订单（order_type = 2）
    //     $this->where('order.order_type', '=', 2);

    //     // 获取列表数据
    //     return $this->alias('m')
    //         ->field('m.*, order.order_no')
    //         ->with(['order_goods.image', 'orderMaster', 'user'])
    //         ->join('order', 'order.order_id = m.order_id')
    //         ->order(['m.create_time' => 'desc'])
    //         ->paginate(10, false, [
    //             'query' => \request()->request()
    //         ]);
    // }
public function getList($query = [])
{
    // ====== 基础筛选 ======
    if (!empty($query['order_no'])) {
        $this->where('o.order_no', 'like', '%' . trim($query['order_no']) . '%');
    }
    if (!empty($query['start_time'])) {
        $this->where('m.create_time', '>=', strtotime($query['start_time']));
    }
    if (!empty($query['end_time'])) {
        $this->where('m.create_time', '<', strtotime($query['end_time']) + 86400);
    }
    if (isset($query['type']) && $query['type'] > 0) {
        $this->where('m.type', '=', (int)$query['type']);
    }
    if (isset($query['state']) && is_numeric($query['state'])) {
        $this->where('m.status', '=', (int)$query['state']);
    }

    // 统一关键字
    $kw = !empty($query['search']) ? trim($query['search']) : '';

    // 就诊人聚合子查询
    $subUjSql = Db::name('user_jiuzhen')
        ->where('is_del', 0)
        ->fieldRaw('
            user_id,
            COALESCE(
                MAX(CASE WHEN is_mr = 1 THEN name  END),
                SUBSTRING_INDEX(GROUP_CONCAT(name  ORDER BY create_time DESC),  ",", 1)
            ) AS name,
            COALESCE(
                MAX(CASE WHEN is_mr = 1 THEN phone END),
                SUBSTRING_INDEX(GROUP_CONCAT(phone ORDER BY create_time DESC), ",", 1)
            ) AS phone
        ')
        ->group('user_id')
        ->buildSql();

    $qb = $this->alias('m')
        ->with(['order_goods.image', 'orderMaster', 'user'])
        // 订单
        ->join(['yoshop_order' => 'o'], 'o.order_id = m.order_id')
        ->where('o.order_type', 2)
        // 推荐关系 & 推荐人
        ->join(['yoshop_dealer_order' => 'do'], 'do.order_id = o.order_id', 'LEFT')
        ->join(['yoshop_user' => 'r'], 'r.user_id = do.first_user_id', 'LEFT')
        ->join([$subUjSql => 'ruj'], 'ruj.user_id = r.user_id', 'LEFT')
        // 买家
        ->join(['yoshop_user' => 'u'], 'u.user_id = o.user_id', 'LEFT')
        ->join([$subUjSql => 'buj'], 'buj.user_id = o.user_id', 'LEFT')
        // 收货地址
        ->join(['yoshop_order_address' => 'oa'], 'oa.order_id = o.order_id', 'LEFT')
        ->field([
            'm.*',
            'o.order_no',

            'r.user_id  AS recommender_id',
            'r.nickname AS recommender_nickname',
            'MAX(ruj.name)  AS recommender_realname',
            'MAX(ruj.phone) AS recommender_phone',

            'u.nickname AS buyer_nickname',
            'MAX(buj.name)  AS buyer_realname',
            'MAX(buj.phone) AS buyer_phone',

            'MAX(oa.name)  AS consignee_name',
            'MAX(oa.phone) AS consignee_phone',
        ]);

    // ====== 关键字搜索 ======
    // ====== 关键字搜索 ======
if ($kw !== '') {
    if ($kw === '平台') {
        $qb->where(function($w){
            $w->where('do.first_user_id', 'EXP', 'IS NULL')
              ->whereOr('do.first_user_id', '=', 0);
        });
    } else {
        $digits = preg_replace('/\D+/', '', $kw);
        $qb->where(function ($w) use ($kw, $digits) {
            $like = '%' . $kw . '%';

            // 推荐人：昵称 / 就诊人姓名 / 手机（原始关键字 + 纯数字）
            $w->where('r.nickname', 'like', $like)
              ->whereOr('ruj.name',  'like', $like)
              ->whereOr('ruj.phone', 'like', $like);       // 新增：原始关键字匹配
            if ($digits !== '') {
                $w->whereOr('ruj.phone', 'like', '%' . $digits . '%');
            }

            // 买家：昵称 / 就诊人姓名 / 手机（原始关键字 + 纯数字）
            $w->whereOr('u.nickname', 'like', $like)
              ->whereOr('buj.name',   'like', $like)
              ->whereOr('buj.phone',  'like', $like);      // 新增：原始关键字匹配
            if ($digits !== '') {
                $w->whereOr('buj.phone', 'like', '%' . $digits . '%');
            }

            // 收货人：姓名 / 手机（原始关键字 + 纯数字）
            $w->whereOr('oa.name',  'like', $like)
              ->whereOr('oa.phone', 'like', $like);        // 新增：原始关键字匹配
            if ($digits !== '') {
                $w->whereOr('oa.phone', 'like', '%' . $digits . '%');
            }
        });
    }
}

    return $qb->group('m.order_refund_id')
        ->order(['m.create_time' => 'desc'])
        ->paginate(10, false, [
            'query' => request()->request()
        ]);
}
    /**
     * 商家审核
     * @param $data
     * @return bool
     */
    public function audit($data)
    {
        if ($data['is_agree'] == 20 && empty($data['refuse_desc'])) {
            $this->error = '请输入拒绝原因';
            return false;
        }
        if ($data['is_agree'] == 10 && empty($data['address_id'])) {
            $this->error = '请选择退货地址';
            return false;
        }
        $this->transaction(function () use ($data) {
            // 拒绝申请, 标记售后单状态为已拒绝
            $data['is_agree'] == 20 && $data['status'] = 10;
            // 同意换货申请, 标记售后单状态为已完成
            $data['is_agree'] == 10 && $this['type']['value'] == 20 && $data['status'] = 20;
            // 更新退款单状态
            $this->allowField(true)->save($data);
            // 同意售后申请, 记录退货地址
            if ($data['is_agree'] == 10) {
                (new OrderRefundAddress)->add($this['order_refund_id'], $data['address_id']);
            }
            // 订单详情
            $order = Order::detail($this['order_id']);
            // 发送消息通知
            MessageService::send('order.refund', [
                'refund' => $this,    // 退款单信息
                'order_no' => $order['order_no'],      // 订单信息
                'order_type' => OrderTypeEnum::MASTER,   // 订单类型
            ]);
        });
        return true;
    }

    /**
     * 确认收货并退款
     * @param $data
     * @return bool
     * @throws \think\exception\DbException
     */
    public function receipt($data)
    {
        // 订单详情
        $order = Order::detail($this['order_id']);
        if ($data['refund_money'] > min($order['pay_price'], $this['order_goods']['total_pay_price'])) {
            $this->error = '退款金额不能大于商品实付款金额';
            return false;
        }
        $this->transaction(function () use ($order, $data) {
            // 更新售后单状态
            $this->allowField(true)->save([
                'refund_money' => $data['refund_money'],
                'is_receipt' => 1,
                'status' => 20
            ]);
            // 消减用户的实际消费金额
            // 条件：判断订单是否已结算
            if ($order['is_settled'] == true) {
                (new UserModel)->setDecUserExpend($order['user_id'], $data['refund_money']);
            }
            // 执行原路退款
            (new RefundService)->execute($order, $data['refund_money']);
            // 发送消息通知
            MessageService::send('order.refund', [
                'refund' => $this,    // 退款单信息
                'order_no' => $order['order_no'],      // 订单信息
                'order_type' => OrderTypeEnum::MASTER,   // 订单类型
            ]);
        });
        return true;
    }

}